const userService = require("../service/user.service");
const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_ALREADY_EXISTS,
} = require("../config/error");
const md5password = require("../utils/md5-password");
const verifyUser = async (ctx, next) => {
  const user = ctx.request.body; //这样拿请求体的数据
  //2.验证客户端传递过来的user是否可以保存到数据库中
  //2.1判断是否有name和password
  const { username, password } = user;
  if (!username || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
  }
  //2.2判断name是否在数据库中已经存在了
  const users = await userService.findUserByName(username);
  if (users.length > 0) {
    return ctx.app.emit("error", NAME_IS_ALREADY_EXISTS, ctx);
  }
  await next();
};
const handlePassword = async (ctx, next) => {
  console.log("开始处理密码");
  const { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);
  console.log("结束处理密码", md5password(password));
  await next();
};
module.exports = { verifyUser, handlePassword };
